package com.mazaiting.course.exception;

import com.mazaiting.course.domain.Response;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/***
 * 注意：在controller层添加通知。如果使用@ControllerAdvice，则方法上需要添加@ResponseBody
 * 捕获所有异常
 * @author danghailiang
 * @datetime 2022/3/8
 *
 */
@Component
@RestControllerAdvice
public class UnifiedExceptionHandler {

    /**
     * 所有controller异常都捕获
     * @param e
     * @return
     */
    @ExceptionHandler(value = {Exception.class})
    public Response getAllException(Exception e){
       return Response.error();
    }

    @ExceptionHandler( value = CustomException.class)
    public Response exceptionHandler(CustomException e){
        return Response.error().message(e.getMessage()).code(e.getCode());
    }

    /**
     * 用户名String username = "zhangsan++--+/,./,-=[]"; 报错异常
     * @param e
     * @return
     */
    @ExceptionHandler( value = IllegalArgumentException.class)
    public Response getInvocationTargetException(CustomException e){

        return Response.error().message(e.getMessage()).code(e.getCode());
    }
}
